package com.refusea.train.mapper

import com.refusea.train.domain.entity.ClassGroup
import com.refusea.train.domain.req.ClassGroupReq
import org.apache.ibatis.annotations.Delete
import org.apache.ibatis.annotations.Insert
import org.apache.ibatis.annotations.Mapper
import org.apache.ibatis.annotations.Options
import org.apache.ibatis.annotations.Param
import org.apache.ibatis.annotations.Select
import org.apache.ibatis.annotations.Update

@Mapper
interface ClassGroupMapper {

    @Insert(
        """
        INSERT INTO class_group 
        (school_id, course_id, classroom_id, name, completed, confirmed_lessons, next_lesson_number) 
        VALUES 
        (#{schoolId}, #{courseId}, #{classroomId}, #{name}, #{completed}, 0, 1)
        """
    )
    @Options(useGeneratedKeys = true, keyProperty = "id")
    fun insert(classGroup: ClassGroup): Int

    @Delete("DELETE FROM class_group WHERE id = #{id} and school_id = #{schoolId}")
    fun delete(@Param("id") id: Int, @Param("schoolId") schoolId: Int): Int

    @Update("UPDATE class_group SET school_id = #{schoolId}, course_id = #{courseId}, name = #{name}, completed = #{completed}, confirmed_lessons = #{confirmedLessons}, next_lesson_number = #{nextLessonNumber} WHERE id = #{id}")
    fun update(classGroup: ClassGroup): Int

    @Select("SELECT * FROM class_group WHERE id = #{id}")
    fun select(id: Int): ClassGroup?

    @Select("SELECT * FROM class_group")
    fun list(): List<ClassGroup>

    @Select("SELECT * FROM class_group where completed=0")
    fun allActive(): List<ClassGroup>

    @Select("SELECT * FROM class_group where school_id = #{schoolId} and completed=0")
    fun active(schoolId: Int): List<ClassGroup>

    @Select("<script>SELECT COUNT(*) FROM class_group WHERE ${ORDER_CONDITION}</script>")
    fun count(req: ClassGroupReq): Int

    @Select("<script>SELECT * FROM class_group WHERE $ORDER_CONDITION LIMIT #{offset}, #{limit}</script>")
    fun query(req: ClassGroupReq): List<ClassGroup>

    @Update("UPDATE class_group SET completed = 0 WHERE id = #{classGroupId} and completed<>1")
    fun completed(classGroupId: Int): Int

    @Update("UPDATE class_group SET confirmed_lessons = confirmed_lessons + #{inc} WHERE id = #{id} and completed = 0")
    fun incConfirmedLessons(@Param("id") id: Int, @Param("inc") inc: Int): Int

    @Update("UPDATE class_group SET next_lesson_number = next_lesson_number + #{inc} WHERE id = #{id} and completed = 0")
    fun incNextLessonNumber(@Param("id") id: Int, @Param("inc") inc: Int): Int

    companion object {
        const val ORDER_CONDITION = """
        school_id = #{schoolId}
        <if test='courseId!=null and courseId!=0'>and course_id = #{courseId}</if>
        <if test='completed!=null'>and completed = #{completed}</if>
        """
    }
}
